package cl.uchile.coupling.web.controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cl.uchile.cos.session.Client;
import cl.uchile.cos.sync.Message;
import cl.uchile.cos.sync.adapters.Adapter;
import cl.uchile.cos.sync.adapters.ServerAdapter;
import cl.uchile.coupling.messaging.JSONBufferAdapter;
import cl.uchile.coupling.resources.MessageFactory;

@Controller
@RequestMapping("/coupling")
public class CouplingController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory
			.getLogger(CouplingController.class);
	@Autowired
	private Client client;
	@Autowired
	private MessageFactory messageFactory;
	private long id = 1;

	@RequestMapping(value = "couple/{ssid}", produces = "application/json", method = RequestMethod.POST)
	public @ResponseBody
	void couple(@RequestParam(required = false) String initState,
			@PathVariable String ssid, @RequestParam String objectId) {
		Adapter adapter = client.getAdapter(ssid);
		Message message = messageFactory.createFromJSON(objectId, initState);
		if (adapter != null) {
			if (message != null) {
				adapter.couple(objectId, message);
				logger.debug("cliente " + client.getId()
						+ " a acoplado el objeto " + objectId
						+ " en la sesion " + ssid + " con estado inicial "
						+ initState);
			} else {
				adapter.couple(objectId);
				logger.debug("cliente " + client.getId()
						+ " a acoplado el objeto " + objectId
						+ " en la sesion " + ssid);
			}
		} else
			logger.warn("cliente " + client.getId()
					+ " no se ha unido a la sesion " + ssid);

	}

	@RequestMapping(value = "decouple/{ssid}", produces = "application/json", method = RequestMethod.POST)
	public @ResponseBody
	void decouple(@PathVariable String ssid, @RequestParam String objectId) {
		Adapter adapter = client.getAdapter(ssid);
		if (adapter != null) {
			adapter.decouple(objectId);
			logger.debug("cliente " + client.getId()
					+ " ha desacoplado el objeto " + objectId
					+ " en la sesion " + ssid);
		} else
			logger.debug("cliente " + client.getId()
					+ " no se ha unido a la sesion " + ssid);
	}

	@RequestMapping(value = "{ssid}", method = RequestMethod.POST)
	public @ResponseBody
	void write(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String ssid,
			@RequestParam(required = false) String objectId) {
		Adapter adapter = client.getAdapter(ssid);
		if (adapter != null) {
			adapter.sendToServer(this.messageFactory.createFromJSON(objectId,
					request.getParameter("message").toString()));
			logger.debug(request.getParameter("message").toString());
		} else
			logger.debug("cliente " + client.getId()
					+ " no se ha unido a la sesion " + ssid);

	}

	@RequestMapping(value = "{ssid}", method = RequestMethod.GET)
	public @ResponseBody
	void read(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String ssid) throws IOException {
		JSONBufferAdapter adapter = (JSONBufferAdapter) client.getAdapter(ssid);

		if (adapter != null) {
			response.addHeader("Content-Type",
					"text/event-stream; charset=utf-8");
			response.addHeader("Cache-Control", "no-cache");
			PrintWriter writer = response.getWriter();
			writer.println("retry: 500");
			writer.println("id: " + id++);
			writer.print("data: ");
			adapter.getMessages(writer);
			writer.print("\n\n");
			writer.flush();
		} else
			logger.debug("cliente " + client.getId()
					+ " no se ha unido a la sesion " + ssid);

	}

}
